package com.atstudy.headline.web.app.service.impl;

import com.atstudy.headline.entity.Users;
import com.atstudy.headline.enums.BaseStatus;
import com.atstudy.headline.exception.HeadlineException;
import com.atstudy.headline.result.ResultCodeEnum;
import com.atstudy.headline.utils.JwtUtil;
import com.atstudy.headline.web.app.mapper.UsersMapper;
import com.atstudy.headline.web.app.service.LoginService;
import com.atstudy.headline.web.app.vo.login.LoginVo;
import com.atstudy.headline.web.app.vo.users.UserLoginInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public String login(LoginVo loginVo) {
        // 登录验证
        Users users = usersMapper.selectOneByUserPhone(loginVo.getPhone());
        if(users==null){
            throw  new HeadlineException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        if (users.getStatus() == BaseStatus.DISABLE) {
            throw  new HeadlineException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        if (!users.getPassword().equals(loginVo.getPassword())) {
            throw  new HeadlineException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        if (!users.getPhone().equals(loginVo.getPhone())) {
            throw  new HeadlineException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //判断用户role_coleshin是否为1
        if (users.getRoleCode() != 1) {
            throw  new HeadlineException(ResultCodeEnum.APP_ACCOUNT_NOT_EXIST_ERROR);
        }
        //登录成功
        System.out.println("aa");
        System.out.println(JwtUtil.createToken(users.getUserId(), users.getPhone()));
        return JwtUtil.createToken(users.getUserId(), users.getPhone());
    }

    @Override
    public UserLoginInfoVo getLoginUserInfoById(Integer userId) {
        Users users = usersMapper.selectById(userId);
        UserLoginInfoVo userLoginInfoVo = new UserLoginInfoVo();
            userLoginInfoVo.setUserId(users.getUserId());
            userLoginInfoVo.setUsername(users.getUsername());
            userLoginInfoVo.setAvatarUrl(users.getAvatarUrl());
            return userLoginInfoVo;
    }

}
